package framework;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ConnectDatabase {
	public static Connection connection = null;

	public static void main(String[] args) {
		System.out.println("Start");
		connectToDB();
		getAllStyleDetails("select s.style_no,s.short_desc,c.client_name from public.style s,public.client c where s.client_id=c.client_id order by style_no");

	}

	public static void connectToDB() {
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return;
		}

		try {
			connection = DriverManager.getConnection(
					"jdbc:postgresql://172.16.1.5:5432/EBUYING-20", "refact_prod",
					"production");
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}

		if (connection != null)
			System.out.println("Connected to DataBase Succesfully");
		else
			System.out.println("Failed to make connection!");

	}

	public static ArrayList<String> getstylelist() {
		ArrayList<String> styleNoDB = new ArrayList<String>();
		try {
			Statement stmt = connection.createStatement();
			ResultSet rs = stmt
					.executeQuery("select style_no from public.style");
			while (rs.next()) {
				styleNoDB.add(rs.getString("style_no"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return styleNoDB;
	}

	public static Map<String, Map<String, Object>> getAllStyleDetails(
			String completeNativeSql) {
		Map<String, Map<String, Object>> finalResultMap = null;

		try {
			Statement stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery(completeNativeSql);
			ResultSetMetaData rsmd = rs.getMetaData();
			int numOfCol = rsmd.getColumnCount();
			System.out.println(" --------- Number of Columns=" + numOfCol);
			finalResultMap = new HashMap<String, Map<String, Object>>();
			while (rs.next()) {
				Map<String, Object> idValuemap = null;
				idValuemap = new HashMap<String, Object>();
				for (int i = 0; i < numOfCol; i++) {
					idValuemap.put(rsmd.getColumnName(i + 1), rs
							.getString(i + 1));
				}
				finalResultMap.put(rs.getString(1), idValuemap);
			}

			Collection c = finalResultMap.values();
			Iterator itr = c.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return finalResultMap;

	}
}
